<?php
class BlogModel extends CI_Model
{
    // Mongo
    const collection = 'blog';
    const sequence_id = 'blog';

    // Cache
    const cache_enable = true;
    const cache_ttl = 86400;
    const prefix_cache_item = 'blog.%s';
    const prefix_cache_list = 'blog.list.%s.%s.%s';
    const prefix_cache_count = 'blog.count.%s';


    public function  __construct()
    {
        parent::__construct();
    }

    public function initData($data)
    {
        // Check $data
        if(!is_array($data)) return null;

        // Define fields
        $fields = array('_id', 'company_id');

        $list = null;

        foreach($fields as $key) {
            if(isset($data[$key])) {
                $list[$key] = $data[$key];
            }
        }

        // Return
        return $list;
    }

    public function insert($data)
    {
        // Init data
        $data = $this->initData($data);

        // Check
        if(empty($data) || !isset($data['company_id'])) return false;

        // Get sequence id
        $CI = &get_instance();
        $CI->load->model('SequenceModel');
        $id = $CI->SequenceModel->getSequence(self::sequence_id);

        if(empty($id)) return false;

        // Set id
        $data['_id'] = $id;

        // Insert to DB
        $rs = $this->mongo_db->insert(self::collection, $data);

        // Check
        if($rs) {

            // Increment
            $CI->SequenceModel->increment(self::sequence_id);

            // Delete cache
            $this->cache->memcached->delete(sprintf(self::prefix_cache_count, $data['company_id']));
            $this->_clearCacheList($data['company_id']);
        }

        return $rs;
    }

    public function update($data)
    {
        // Init data
        $data = $this->initData($data);

        // Check
        if(empty ($data) || empty($data['_id']) || empty($data['company_id'])) return false;

        $rs = $this->mongo_db->update(self::collection, $data);

        // Check
        if($rs) {

            // Delete cache
            $this->cache->memcached->delete(sprintf(self::prefix_cache_item, $data['_id']));
            $this->_clearCacheList($data['company_id']);
        }

        // Return
        return $rs;
    }

    public function delete($id)
    {
        // Check
        if(empty($id)) return false;

        // Get
        $data = $this->selectProduct($id);

        if(empty($data['_id'])) return false;

        // Delete
        $rs = $this->mongo_db->where(array('_id' => $id))->delete(self::collection);

        // Check
        if($rs) {

            // Clear cache
            $this->cache->memcached->delete(sprintf(self::prefix_cache_item, $data['_id']));
            $this->cache->memcached->delete(sprintf(self::prefix_cache_count, $data['company_id']));
            $this->_clearCacheList($data['company_id']);
        }

        // Return
        return $rs;
    }

    public function selectPost($id)
    {
        // Check
        if(empty($id)) return false;

        // Init
        $data = false;

        // Cache key
        $cacheKey = sprintf(self::prefix_cache_item, $id);

        // Read cache
        if(self::cache_enable) {
            $data = $this->cache->memcached->get($cacheKey);
        }

        // Check
        if($data === false) {

            // Select from DB
            $data = $this->mongo_db->where(array('_id' => $id))->findOne(self::collection);

            // Write to cache
            $this->cache->memcached->save($cacheKey, $data, 0, self::cache_ttl);
        }

        // Return
        return $data;
    }

    public function selectPostList($companyId, $page)
    {
        $list = false;

        // Check
        if(empty($companyId) || empty($page)) return $list;

        // Create cache key
        $cacheKey = sprintf(self::prefix_cache_list, $companyId, $page, FE_BLOG_LIMIT);

        // Read cache
        if(self::cache_enable) {
            $list = $this->cache->memcached->get($cacheKey);
        }

        if($list === false) {

            // Set offset
            $offset = ($page - 1) * FE_BLOG_LIMIT;

            // Select
            $list = $this->mongo_db->where(array('company_id' => $companyId))->offset($offset)->limit(FE_BLOG_LIMIT)->get(self::collection);

            // Write to cache
            $this->cache->memcached->save($cacheKey, $list, 0, self::cache_ttl);
        }

        // Return
        return $list;
    }

    public function selectTotalPost($id)
    {
        // Check
        if(empty($id)) return 0;

        // Init data
        $total = 0;

        // Create cache key
        $cacheKey = sprintf(self::prefix_cache_count, $id);

        // Read cache
        if(self::cache_enable) {
            $total = $this->cache->memcached->get($cacheKey);
        }

        // Check
        if($total === false) {

            // Select
            $total = $this->mongo_db->where(array('company_id' => $id))->count();

            // Write to cache
            $this->cache->memcached->save($cacheKey, $total, self::cache_ttl);
        }
        // Return
        return $total;
    }

    private function _clearCacheList($companyId)
    {
        // Check
        if(empty($companyId)) return false;

        $total = $this->selectTotalPost($companyId);

        // Check
        if($total == 0) return false;

        // Set page number
        $total = ceil($total / FE_BLOG_LIMIT);

        // Delete cache
        for($i = 1; $i < $total; $i++) {
            $this->cache->memcached->delete(sprintf(self::prefix_cache_list, $companyId, $i, FE_BLOG_LIMIT));
        }

        // Return
        return true;
    }
}
?>